<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>关键字输入提示</title>
</head>
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&libraries=service&key={$tencent_map_web_service_key|htmlentities}"></script>
<style type="text/css">
    html,
    body {
        height: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden;
        font-family: Arial, sans-serif;
        background-color: #f0f0f0; /* Light background for contrast */
    }
    #container {
        position: relative;
        width: 100%;
        height: 100%;
    }
    #panel {
        position: absolute;
        background: #FFF;
        width: 350px;
        padding: 20px;
        z-index: 9999;
        top: 30px;
        left: 30px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Add shadow for depth */
        border-radius: 8px; /* Rounded corners */
    }
    .input-group {
        display: flex; /* Use flexbox for alignment */
        justify-content: space-between; /* Space between elements */
        margin-bottom: 10px; /* Space below the input group */
    }
    #citySelect, #keyword {
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        transition: border-color 0.3s;
        flex: 1; /* Allow inputs to grow */
        margin-right: 10px; /* Space between dropdown and search input */
    }
    #citySelect:hover, #keyword:hover {
        border-color: #007bff; /* Change border color on hover */
    }
    #keyword:focus {
        border-color: #007bff; /* Change border color on focus */
        outline: none; /* Remove default outline */
    }
    #search {
        background-color: #007bff; /* Button background color */
        color: white; /* Button text color */
        border: none; /* Remove border */
        cursor: pointer; /* Pointer cursor on hover */
        padding: 10px; /* Button padding */
        border-radius: 5px; /* Rounded corners */
        transition: background-color 0.3s; /* Smooth background transition */
    }
    #search:hover {
        background-color: #0056b3; /* Darker shade on hover */
    }
    #suggestionList {
        list-style-type: none;
        padding: 0;
        margin: 0;
        max-height: 200px; /* Limit height */
        overflow-y: auto; /* Scroll if too many suggestions */
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        border-radius: 5px;
        background-color: white; /* Background for suggestion list */
    }
    #suggestionList li {
        padding: 10px; /* Padding for list items */
    }
    #suggestionList li a {
        text-decoration: none;
        color: black;
        display: block;
        transition: background-color 0.3s; /* Smooth background transition */
    }
    #suggestionList li a:hover {
        background-color: #f0f0f0; /* Light background on hover */
    }
    #suggestionList li .item_info {
        font-size: 12px;
        color: grey;
    }
    .info {
        text-align: left; /* Left-align the text */
        font-family: Arial, sans-serif; /* Set a default font */
        margin: 10px; /* Add some margin for spacing */
        padding-left: 0; /* Remove any left padding */
    }
    .info strong {
        display: inline-block; /* Keep labels and values in line */
        margin-right: 5px; /* Reduced margin between label and value */
    }
    .info span {
        display: inline; /* Change to inline to remove unnecessary space */
    }
</style>

<body>
<div id="container"></div>
<div id="panel">
    <!--    <p>请在右侧示例代码第10行填入您的key，并执行查看运行结果（key可在控制台应用管理中自行创建）</p>-->
    <!--    <p>输入关键字，将展示相关地点提示，点击提示可定位到该处。</p>-->
    <div class="input-group">
        <!-- 城市切换下拉框 -->
        {if !empty($cityList)}
        <select id="citySelect" onchange="changeCity()">
            {volist name="cityList" id="vo"}
            <option value="{$vo.area.shortname|htmlentities}" data-lat="{$vo.area.lat|htmlentities}" data-lng="{$vo.area.lng|htmlentities}">{$vo.area.shortname|htmlentities}</option>
            {/volist}
        </select>
        {/if}
        <input id='keyword' type="text" value='' oninput="getSuggestions()" placeholder="输入关键字..." />
<!--        <input id="search" type="button" class="btn" value="搜索" onclick="searchByKeyword()" />-->
    </div>
    <ul id="suggestionList"></ul>
</div>
</body>

<script type="text/javascript">
    var map = new TMap.Map('container', {
        zoom: 17,
        center: new TMap.LatLng({$defaultTMapLatLng|htmlentities}), // 默认中心位置：北京
        pitch: 70, // 设置地图的倾斜角度为 70度，启用3D视图
        tilt: 70,  // 设置地图倾斜角度
        rotation: 0, // 控制地图的旋转角度
    });
    // 初始化marker，增加每个标记的名字和地址
    var json_geometries_array = {$json_geometries_array};

    var geometries_result = [];

    // Iterate over the json_geometries_array
    json_geometries_array.forEach(item => {
        // Push a new object to the result array
        geometries_result.push({
            id: 'demo' + item.id, // Unique ID
            styleId: 'marker', // Static styleId
            position: new TMap.LatLng(item.driver_lat, item.driver_lng), // Create a new LatLng object
            properties: {
                name: item.properties.name, // Use the name from the item
                acceptance_number: item.properties.acceptance_number,
                total_pay_amount: item.properties.total_pay_amount
            }
        });
    });


    var marker = new TMap.MultiMarker({
        id: 'marker-layer',
        map: map,
        styles: {
            "marker": new TMap.MarkerStyle({
                "width": 50,
                "height": 50,
                "anchor": { x: 35, y: 35 },
                "src": '{$markerDefault|htmlentities}'
            })
        },



        geometries: geometries_result
    });


    // 初始化infoWindow
    var infoWindow = new TMap.InfoWindow({
        map: map,
        position: new TMap.LatLng({$defaultTMapLatLng|htmlentities}),
        offset: { x: 0, y: -32 } // 设置信息窗相对position偏移像素
    });
    infoWindow.close(); // 初始时关闭信息窗

    // 监听标注点击事件
    marker.on("click", function (evt) {
        // 获取标记的名字和地址
        var name = evt.geometry.properties.name;
        var acceptance_number = evt.geometry.properties.acceptance_number;
        var total_pay_amount = evt.geometry.properties.total_pay_amount;

        // 设置infoWindow内容
        var content = "<div class='info'><strong>代驾师傅:</strong><span> " + name + "</span><br>" +
                      "<strong>接单数量:</strong><span> " + acceptance_number + "</span><br>" +
                      "<strong>接单金额:</strong><span> " + total_pay_amount + "</span></div>";
        infoWindow.setContent(content); // 设置信息窗内容
        infoWindow.setPosition(evt.geometry.position); // 设置信息窗位置
        infoWindow.open(); // 打开信息窗
    });

    var suggestionList = [];
    var search = new TMap.service.Search({ pageSize: 10 }); // 新建一个地点搜索类
    var suggest = new TMap.service.Suggestion({
        pageSize: 10, // 返回结果每页条目数
        region: '{$region|htmlentities}', // 初始城市范围
        regionFix: true, // 搜索无结果时是否固定在当前城市
    });
    var markers = new TMap.MultiMarker({
        map: map,
        geometries: [],
    });
    var infoWindowList = Array(10);

    function changeCity() {
        var selectedCity = document.getElementById("citySelect").value;
        var lat = parseFloat(document.querySelector(`#citySelect option[value="${selectedCity}"]`).getAttribute("data-lat"));
        var lng = parseFloat(document.querySelector(`#citySelect option[value="${selectedCity}"]`).getAttribute("data-lng"));
        map.setCenter(new TMap.LatLng(lat, lng)); // Center the map on the selected city
        suggest.region = selectedCity; // Update the search region
    }

    function getSuggestions() {
        var suggestionListContainer = document.getElementById('suggestionList');
        suggestionListContainer.innerHTML = '';
        var keyword = document.getElementById('keyword').value;
        if (keyword) {
            suggest
                .getSuggestions({ keyword: keyword, location: map.getCenter() })
                .then((result) => {
                    suggestionListContainer.innerHTML = '';
                    suggestionList = result.data;
                    suggestionList.forEach((item, index) => {
                        suggestionListContainer.innerHTML += `<li><a href="#" onclick="setSuggestion(${index})">${item.title}<span class="item_info">${item.address}</span></a></li>`;
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        }
    }

    function setSuggestion(index) {
        infoWindowList.forEach((infoWindow) => {
            infoWindow.close();
        });
        infoWindowList.length = 0;
        document.getElementById('keyword').value = suggestionList[index].title;
        document.getElementById('suggestionList').innerHTML = '';
        markers.setGeometries([]);
        markers.updateGeometries([
            {
                id: '0',
                position: suggestionList[index].location,
            },
        ]);
        var infoWindow = new TMap.InfoWindow({
            map: map,
            position: suggestionList[index].location,
            content: `<h3>${suggestionList[index].title}</h3><p>地址：${suggestionList[index].address}</p>`,
            offset: { x: 0, y: -50 },
        });
        infoWindowList.push(infoWindow);
        map.setCenter(suggestionList[index].location);
        markers.on('click', (e) => {
            infoWindowList[Number(e.geometry.id)].open();
        });
    }

    function searchByKeyword() {
        infoWindowList.forEach((infoWindow) => {
            infoWindow.close();
        });
        infoWindowList.length = 0;
        markers.setGeometries([]);
        search
            .searchRectangle({
                keyword: document.getElementById('keyword').value,
                bounds: map.getBounds(),
            })
            .then((result) => {
                result.data.forEach((item, index) => {
                    var geometries = markers.getGeometries();
                    var infoWindow = new TMap.InfoWindow({
                        map: map,
                        position: item.location,
                        content: `<h3>${item.title}</h3><p>地址：${item.address}</p><p>电话：${item.tel}</p>`,
                        offset: { x: 0, y: -50 },
                    });
                    infoWindow.close();
                    infoWindowList[index] = infoWindow;
                    geometries.push({
                        id: String(index),
                        position: item.location,
                    });
                    markers.updateGeometries(geometries);
                    markers.on('click', (e) => {
                        infoWindowList[Number(e.geometry.id)].open();
                    });
                });
            });
    }
</script>

</html>